package conexiones;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class Unirse implements Runnable { 
	int puerto;
	InetAddress ipCast;
	Activity act=null;
	Handler handler;
	public Unirse(int port,Handler hand ,Activity actividad){
		puerto=port;
		act=actividad;
		handler=hand;
		
	}
  
    public void run() { 
        try { 
        	String serverIp=getLocalIpAddress();
            if (serverIp != null) { 
            	MulticastSocket ms=new MulticastSocket(puerto);
				InetAddress ip=InetAddress.getByName("225.69.69.85");
				ms.joinGroup(ip);
				DatagramPacket data=new DatagramPacket(serverIp.getBytes(), serverIp.length());
				ms.send(data);
				final String aux=serverIp;
                handler.post(new Runnable() { 
                    @Override
                    public void run() { 
//                		TextView tv=(TextView)act.findViewById(R.id.textView2);
//    					tv.setText("enviado"+" "+aux);
                    } 
                });
            }
        } catch (Exception e) { 
            handler.post(new Runnable() { 
                @Override
                public void run() { 
//                	TextView tv=(TextView)act.findViewById(R.id.textView2);
//					tv.setText("error"); 
                } 
            }); 
            e.printStackTrace(); 
        } 
    }  
    
    private String getLocalIpAddress() { 
	    try { 
	        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { 
	            NetworkInterface intf = en.nextElement(); 
	            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { 
	                InetAddress inetAddress = enumIpAddr.nextElement(); 
	                if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); } 
	            } 
	        } 
	    } catch (SocketException ex) { 
	        Log.e("ServerActivity", ex.toString()); 
	    } 
	    return null; 
    }
}
